package com.example.wkable.exoplayer.player

import android.net.Uri
import com.example.wkable.exoplayer.AppContext
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util

class MyExoPlayer(private val player: ExoPlayer) : BasePlayer<ExoPlayer> {

    private val listeners: ArrayList<BasePlayer.EventListener> = ArrayList()

    init {
        player.addListener(object : Player.EventListener {
            override fun onLoadingChanged(isLoading: Boolean) {
            }

            override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
                listeners.forEach {
                    it.onStateChange(playbackState)
                }
            }

            override fun onPlayerError(error: ExoPlaybackException?) {
                listeners.forEach {
                    it.onError("$error")
                }
            }
        })
    }

    override fun release() {
        if (player.playbackState != Player.STATE_IDLE) {
            player.stop()
            player.release()
        }
    }

    override fun start(url: Uri, loop: Boolean) {
        player.prepare(
            ExtractorMediaSource.Factory(
                DefaultDataSourceFactory(
                    AppContext.context,
                    Util.getUserAgent(AppContext.context, AppContext.context!!.packageName)
                )
            ).createMediaSource(
                url
            )
        )
        player.repeatMode = if (loop) {
            Player.REPEAT_MODE_ONE
        } else {
            Player.REPEAT_MODE_OFF
        }
        player.playWhenReady = true
    }

    override fun resume() {
        if (player.playbackState == Player.STATE_READY) {
            player.playWhenReady = true
        }
    }

    override fun pause() {
        if (player.playbackState == Player.STATE_READY) {
            player.playWhenReady = false
        }
    }

    override fun addListener(listener: BasePlayer.EventListener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener)
        }
    }

    override fun removeListener(listener: BasePlayer.EventListener) {
        listeners.remove(listener)
    }

    override fun getDuration(): Long {
        return player.duration
    }

    override fun seekTo(positionMs: Long) {
        player.seekTo(positionMs)
    }

}